<script setup lang="ts">
    import { ref, reactive, toRefs,defineAsyncComponent,onMounted } from 'vue';
    import { isUsername, isPassword } from '@/utils/validate';
    import { useAuthStore } from '@/stores/auth';
    import { useRouter, useRoute } from 'vue-router';
    import { Session } from '@/utils/storage';
    import type { FormRules } from 'element-plus/es/components/form/src/types';
    import menu from "@/utils/menu";
    const Valicode=defineAsyncComponent(()=>import('@/views/login/valicode.vue'));
    const authStore = useAuthStore();

    const router = useRouter();
    const route = useRoute();

    const formRef = ref();

    const state = reactive({
        loading: false,
        registerloading:false,
        dialogFormVisible:false,
        loginData: {
zhanghao: '',
mima: '',
role: ''
} as unknown as LoginData,
        tableName:''
    });

    const menus = menu.list();

    const { loading, loginData,tableName,dialogFormVisible } = {...toRefs(state)};

    /**
     * 校验用户名是否合法
     * @param rule
     * @param value
     * @param callback
     */
    // function checkzhanghao(rule: any, value: string, callback: Function) {
    //    if (!value) return callback(new Error('请输入有效帐号/手机号！'));
    //    if (!iszhanghao(value)) return callback(new Error('输入的格式不正确，请重新输入！'));
    //    callback(); // 通过
    // }
    /**
     * 校验密码是否合法
     */
// function checkPassword(rule: any, value: string, callback: Function) {
//     if(!value) return callback(new Error('请输入有效密码！'));
//     if(!isPassword(value))  return callback(new Error('密码输入错误，请重新输入！'));
//     callback();// 通过
// }

    const code = ref('')
    const getCode=(value:any)=> {
        code.value = value
        console.log(value);
    }


    function yzcode(rule: any, value: string, callback: Function){
        // if(!value) return callback(new Error('请输入验证码！'));

        console.log(code.value);

        if (!value) {
            return  callback(new Error('请输入验证码'))
        }
        setTimeout(() => {
            if (value != code.value) {
            callback(new Error('验证码有误'))
        }else {
            callback()
        }
    }, 500)



    }




    // 提交登录
    function login() {
        formRef.value.validate(async (valid:boolean) => {
            if (!valid) return;
            try {

                for (let i = 0; i < menus.length; i++) {
                    if (menus[i].roleName == loginData.value.role) {
                        state.tableName = menus[i].tableName;
                    }
                }


                state.loading = true;


                //     // 登录中


                // 触发action，发送登录请求
                const res = await authStore.userLogin(state.loginData,`/yonghu/login`);
                // console.log('submitForm', res);
                // 跳转到来源地址  login?redirect=/home
                Session.set("tableName",state.tableName);
                Session.set("role", state.loginData.role);
                Session.set("adminName", state.loginData.zhanghao);
                // router.replace({path: <string>route.query?.redirect || '/'});
                window.location.reload();
            } catch (error) {
            } finally {
                setTimeout(() => {
                    state.loading = false;
            }, 300);
            }

        });
    }
    function showlogin(){
        state.dialogFormVisible=true;
    }

    defineExpose({
        showlogin
    })

</script>

<template>






    <el-dialog v-model="dialogFormVisible" title="登录" width="500">
        <el-form ref="formRef" :model="loginData" >

            <el-form-item label="账号" prop="zhanghao" :rules="{required: true, message:'账号不能为空' , trigger: 'blur'}">
                <el-input style="width: 300px;" v-model="loginData.zhanghao" />
            </el-form-item>
            <el-form-item label="密码" prop="mima" :rules="{required: true, message:'密码不能为空' , trigger: 'blur'}">
                <el-input style="width: 300px;" v-model="loginData.mima" />
            </el-form-item>
            <el-form-item label="验证码"  prop="valicode" :rules="{required: true, validator: yzcode, trigger: 'blur'}">
                <el-input style="width: 200px;" v-model="loginData.valicode" type="text" placeholder="验证码"/>
                <valicode ref="refresh" @getCode="getCode"/>
            </el-form-item> 
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: center;">
                <el-button @click="dialogFormVisible = false">关闭</el-button>
                <el-button type="primary" @click="login()">
                    登录
                </el-button>
            </div>
        </template>
    </el-dialog>




</template>

<style lang="scss" scoped>

</style>
